import React, { Component } from 'react'
import ReactDOMServer from 'react-dom/server';
import { connect } from 'dva';
import { formatMessage } from 'umi-plugin-locale'
import LeftSider from '@/components/LeftSider'
import BizIcon from '@/components/BizIcon'
import { Tabs, Radio, Modal, Button, Table, Avatar } from 'antd';
import { setFullScreen } from '@/utils/utils'
import DeviceInfo from './components/DeviceInfo'
import {
    DownOutlined,
    UpOutlined
} from '@ant-design/icons';

// import ContextMenu from '@/components/ContextMenu';
import KMap from '@/utils/KMap'
import styles from './index.less'

const map = window.localStorage.getItem('MAP')
const tilesHost = window.localStorage.getItem('MAP_TILES_HOST')
const secretKey = window.localStorage.getItem('MAP_SECRET_KEY')

const { TabPane } = Tabs;
@connect(({ device, config, loading }) => ({
    device,
    config,
    loading: loading.models.config,
    loadingDevice: loading.effects['device/fetchDeviceInfo'],
}))

class LiveLocation extends Component {

    columns = [
        {
            title: '警员姓名',
            dataIndex: 'realname',
            key: 'realname',
            width: 150,
            render: (text, record) => {
                return (
                    <div className="flex inline-item">
                        <Avatar size="40" src={record.photo} />
                        <div style={{ marginLeft: '10px', fontWeight: 'bold' }}>{record.realname}</div>
                    </div>

                )
            }
        },
        {
            title: '警员编号',
            dataIndex: 'policeNo',
            key: 'policeNo',
            width: 100
        },
        {
            title: '设备编号',
            dataIndex: 'sn',
            key: 'sn',
            width: 100
        },
        {
            title: '经纬度',
            dataIndex: 'lng',
            key: 'lng',
            render: (text, record) => {
                return (
                    <div>
                        <div>经度：{record.lng}</div>
                        <div>纬度：{record.lat}</div>
                    </div>
                )
            }
        },
        // {
        //     title: '操作',
        //     key: 'action',
        //     align: "center",
        //     width: 100,
        //     render: (text, record) => (
        //         <span>
        //             <a href="#play" disabled={record.enable === 0} onClick={() => { this.handlePlay(record) }}>播放</a>
        //         </span>
        //     ),
        // },
    ];

    state = {
        mapCfg: {
            zoom: 15,
            minZoom: 1,
            maxZoom: 19,
            center: {
                lng: 104.06751612201126,
                lat: 30.55540009918001
            },
            mapStyle: 'normal',
            tileLayerUrl: tilesHost,
            secretKey: secretKey,
            showExtraLayer: true,
        },
        currentAction: 'move',
        expand: false,
        showSelectModal: false,
        selectedDevice: []
    }
    constructor(props) {
        super(props);
        this.mapRef = React.createRef();
    }

    timer = null

    componentDidMount = () => {

        const { id, sn } = this.props.location.query

        this.props.dispatch({
            type: 'config/fetch',
            callback: (res) => {
                this.setState({
                    mapCfg: {
                        ...this.state.mapCfg,
                        zoom: res.mapZoom || this.state.mapCfg.zoom,
                        center: {
                            lng: parseFloat(res.mapCenterLng) || this.state.mapCfg.center.lng,
                            lat: parseFloat(res.mapCenterLat) || this.state.mapCfg.center.lat,
                        }
                    }
                }, () => {
                    this.initMap();
                    if (id != undefined) {
                        setTimeout(() => {
                            this.getDeviceInfo(id, data => {
                                this.map.setCenter({ lng: data.lng, lat: data.lat })
                                this.setState({
                                    center: {
                                        lng: data.lng,
                                        lat: data.lat
                                    }
                                })
                            });

                            this.deviceList()
                        }, 1000)
                    }
                    this.timer = setInterval(() => this.deviceList(), 5000)
                })
            }
        })

    }

    componentWillUnmount() {
        this.timer && clearInterval(this.timer);
    }

    initMap = () => {
        this.map = new KMap('mapContainer', this.state.mapCfg)
    }

    deviceList = () => {
        this.props.dispatch({
            type: 'device/fetchDeviceList',
            payload: {
            },
            callback: ({ data }) => {
                // 清除所有覆盖物，重新创建覆盖物
                this.map.clearCustomOverlay();
                data.forEach((item) => {
                    let photo = item.photo || "/images/baidu_police.png"
                    let overlayOptions = {
                        icon: window.KMap.Icons.ICON_POLICE,
                        point: {
                            lng: item.lng,
                            lat: item.lat
                        },
                        data: {
                            ...item
                        },
                        click: () => {
                            this.setState({
                                expand: true
                            })
                            this.getDeviceInfo(item.id)
                        }
                    }
                    if (map === 'esri') {
                        overlayOptions.offset = {
                            x: 0,
                            y: 24
                        };
                        overlayOptions.label = {
                            showBg: true,
                            text: item.realname,
                            size: '10px',
                            color: [255, 255, 255]
                        }
                    }
                    if (map === 'baidu_online' || map === 'baidu_offline' || map === 'mapbox') {
                        overlayOptions.offset = {
                            x: -30,
                            y: -32
                        };
                        overlayOptions.content = ReactDOMServer.renderToString(
                            <div className={styles.avatarOverlay}>
                                <img alt="" src={photo} />
                                <div className={styles.content}>
                                    <div className={styles.name}>{item.realname}</div>
                                    {/* <div className={styles.policeNo}>{item.policeNo}</div> */}
                                </div>
                            </div>
                        );
                    }
                    this.map.addCustomOverlay(overlayOptions)
                })
            }
        })
    }

    getDeviceInfo(deviceId, callback) {
        this.props.dispatch({
            type: 'device/fetchDeviceInfo',
            payload: {
                id: deviceId,
                from: 'location'
            },
            callback: res => {
                if (callback != undefined) {
                    callback(res.data)
                }
            }
        })
    }

    onDoubleClick = (selectedKeys, item) => {
        if (item.isOnline === 0) {
            Modal.warning({
                content: formatMessage({ 'id': 'device.offline' })
            })
        } else if (item.isDisabled === 1) {
            Modal.warning({
                content: formatMessage({ 'id': 'device.disabled' })
            })
        } else {
            this.getDeviceInfo(selectedKeys, data => {
                this.map.setCenter({ lng: data.lng, lat: data.lat })
                this.setState({
                    center: {
                        lng: data.lng,
                        lat: data.lat
                    }
                })
            });
        }
    }

    onCheck(selectedNodes, current) {

        if(current.type == 1) {
            this.getDeviceInfo(current.key, data => {
                this.setState({
                    center: {
                        lng: data.lng,
                        lat: data.lat
                    }
                }, () => {
                    this.map.setCenter({ lng: data.lng, lat: data.lat })
                })
            });
        } else {
            selectedNodes.length && selectedNodes.forEach(item => {
                // this.getDeviceInfo(item.key, data => {
                //     this.setState({
                //         center: {
                //             lng: data.lng,
                //             lat: data.lat
                //         }
                //     }, () => {
                //         this.map.setCenter({ lng: data.lng, lat: data.lat })
                //     })
                // });
            })
        }

    }

    onRightClick = (node) => {

    }

    changeMapStyle = (e) => {
        this.map.setMapStyle(e.target.value)
    }

    boxSelect() {
        this.map.boxSelect({}, res => {

            if (res.length) {
                let selectedDevice = res.map((item, index) => {
                    return item.data;
                })
                this.setState({
                    showSelectModal: true,
                    selectedDevice
                })

            }
        })
    }

    handleCancel() {
        this.setState({
            showSelectModal: false
        })
    }

    mapAction(action = 'move') {
        this.setState({
            currentAction: action
        })
        switch (action) {
            case 'move':
                this.map.move()
                break;
            case 'distance':
                this.map.move()
                this.map.distance()
                break;
            case 'zoomOut':
                this.map.boxZoomOut()
                break;
            case 'zoomIn':
                this.map.boxZoomIn()
                break;
            case 'select':
                this.boxSelect()
                break;

            default:
                this.map.move()
        }
    }
    setFullscreen = () => {
        setFullScreen(this.mapView);
    }

    onToggleExpand = () => {
        this.setState({
            expand: !this.state.expand
        })
    }


    render() {
        let { deviceInfo } = this.props.device

        return (
            <div className='wrapper'>

                {/* 左边的列表模块 */}
                <div className='left-sider'>
                    <LeftSider
                        // checkable={true}
                        onRightClick={this.onRightClick.bind(this)}
                        onDoubleClick={this.onDoubleClick.bind(this)}
                        // onCheck={this.onCheck.bind(this)}
                    />
                </div>

                {/* 地图模块部分 */}
                <div className={styles.mapWrapper}>

                    <div style={{ display: 'flex', flexDirection: 'column', flex: 1, height: '100%' }}>
                        <div className={styles.toolsBar}>
                            <ul className={styles.changeMode}>
                            </ul>
                            <ul className={styles.toolsIcon}>
                                {/* <li className={this.state.currentAction === 'move' ? styles.active : ''} onClick={this.mapAction.bind(this, 'move')}>
                                    <BizIcon className={styles.toolsIcon} type="icon-hand-paper" />
                                    <span>{formatMessage({ 'id': 'liveLocation.move' })}</span>
                                </li>
                                <li className={this.state.currentAction === 'zoomIn' ? styles.active : ''} onClick={this.mapAction.bind(this, 'zoomIn')}>
                                    <BizIcon className={styles.toolsIcon} type="icon-zoom-in" />
                                    <span>{formatMessage({ 'id': 'liveLocation.zoomIn' })}</span>
                                </li>
                                <li className={this.state.currentAction === 'zoomOut' ? styles.active : ''} onClick={this.mapAction.bind(this, 'zoomOut')}>
                                    <BizIcon className={styles.toolsIcon} type="icon-zoom-out" />
                                    <span>{formatMessage({ 'id': 'liveLocation.zoomOut' })}</span>
                                </li> */}
                                {
                                    (map === 'baidu_online' || map === 'baidu_offline') && (
                                        <li className={this.state.currentAction === 'distance' ? styles.active : ''} onClick={this.mapAction.bind(this, 'distance')}>
                                            <BizIcon className={styles.toolsIcon} type="icon-distance" />
                                            <span>{formatMessage({ 'id': 'liveLocation.distance' })}</span>
                                        </li>
                                    )
                                }
                                {
                                    (map === 'baidu_online' || map === 'baidu_offline') && (
                                        <li className={this.state.currentAction === 'select' ? styles.active : ''} onClick={this.mapAction.bind(this, 'select')}>
                                            <BizIcon className={styles.toolsIcon} type="icon-square-o" />
                                            <span>{formatMessage({ 'id': 'liveLocation.select' })}</span>
                                        </li>
                                    )
                                }

                                <li onClick={this.setFullscreen.bind(this)}>
                                    <BizIcon className={styles.toolsIcon} type="icon-fullscreen" />
                                    <span>{formatMessage({ 'id': 'liveLocation.fullscreen' })}</span>
                                </li>
                            </ul>
                        </div>

                        <div className={styles.map} ref={node => this.mapView = node}>
                            {
                                map === 'baidu_online' && (
                                    <div style={{ position: 'absolute', top: '10px', right: '10px', zIndex: 1001 }}>
                                        <Radio.Group defaultValue="normal" buttonStyle="solid" size="small" onChange={this.changeMapStyle}>
                                            <Radio.Button value="normal">
                                                <BizIcon type="icon-taiyang" />
                                            </Radio.Button>
                                            <Radio.Button value="dark">
                                                <BizIcon type="icon-moon" />
                                            </Radio.Button>
                                        </Radio.Group>

                                    </div>
                                )
                            }

                            <div id="mapContainer" ref={this.mapRef} style={{ width: '100%', height: '100%' }}></div>
                        </div>
                    </div>

                    <div className={`${styles.tabWrapper} ${this.state.expand ? styles.expand : ''}`}>
                        <Tabs defaultActiveKey="1" className="flex-item" tabBarExtraContent={<Button size="small" onClick={this.onToggleExpand.bind(this)} type="default" icon={this.state.expand === true ? <DownOutlined /> : <UpOutlined />} />}>
                            <TabPane tab="设备信息" key="1">
                                {
                                    deviceInfo && <DeviceInfo deviceInfo={deviceInfo} />
                                }

                            </TabPane>
                            {/* <TabPane tab="报警信息" key="2">
                                    Content of Tab Pane 2
                                    </TabPane>
                                <TabPane tab="媒体文件" key="3">
                                    Content of Tab Pane 3
                                    </TabPane> */}
                        </Tabs>
                    </div>
                </div>

                <Modal
                    title="选中设备"
                    width={800}
                    visible={this.state.showSelectModal}
                    footer={null}
                    keyboard={true}
                    onCancel={this.handleCancel.bind(this)}
                >
                    <Table
                        scroll={{ y: 300 }}
                        columns={this.columns}
                        size="small"
                        rowKey={record => record.id}
                        bordered
                        dataSource={this.state.selectedDevice}
                        pagination={false}
                    />
                </Modal>
                {/* <ContextMenu menu={[
                    { title: '11111111' },
                    { title: '22222222' },
                    { title: '33333333' },
                    { title: '44444444' },
                    { title: '55555555' },
                ]} /> */}
            </div>
        )
    }
}
export default LiveLocation
